package com.molichuxing.services.infrastructure.service.impl;

import javax.annotation.Resource;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.molichuxing.framework.result.ResponseResult;
import com.molichuxing.framework.utils.UUIDUtil;
import com.molichuxing.services.business.dto.request.create.MobileCreateDto;
import com.molichuxing.services.infrastructure.bean.FicoCreditInvestigationBean;
import com.molichuxing.services.infrastructure.dao.FicoCreditInvestigationDao;
import com.molichuxing.services.infrastructure.service.FicoCreditInvestigationService;
import com.molichuxing.services.sdk.fico.FicoLib;

@Service("ficoCreditInvestigationService")
public class FicoCreditInvestigationServiceImpl implements FicoCreditInvestigationService {

	private static final Logger logger = LoggerFactory.getLogger(FicoCreditInvestigationServiceImpl.class);

//	@Value("${verify.days}")
//	private Integer verifyDays;
	
	@Resource
	private FicoCreditInvestigationDao ficoCreditInvestigationDao;

	/**
	 * fico征信
	 * @param createDto
	 * @return
	 */
	@Override
	public ResponseResult<String> creditInvestigation(MobileCreateDto createDto) {
		ResponseResult<String> response = new ResponseResult<>();
		String responseXml = null;
//		if(selectCreditByCondition(createDto)) {
//			return response.success();
//		}
		FicoCreditInvestigationBean insertBean = new FicoCreditInvestigationBean();
		try {
			String idNumber = createDto.getIdNumber();
			String fullName = createDto.getRealName();
			String phoneNumber = createDto.getPhone();
			String serialNumber = UUIDUtil.getUUID();

			insertBean.setIdNumber(idNumber);
			insertBean.setFullName(fullName);
			insertBean.setPhoneNumber(phoneNumber);
			insertBean.setCarPrice(59800);
			insertBean.setBusType(1);
			insertBean.setBussnessId(serialNumber);
			insertBean.setProduct("BQ");

			responseXml = FicoLib.creditInvestigation(phoneNumber, idNumber, fullName, serialNumber, 1, 59800 / 1000);// 例子：80代表8万
			logger.info("【征信接口日志】:" + responseXml);
			insertBean.setResponse(responseXml);
		} catch (Exception e) {
			logger.error("【征信接口异常】", e);
			insertBean.setExceptionMessage(e.toString());
			insertBean.setExceptionState(1);
			ficoCreditInvestigationDao.insert(insertBean);
			response.setCode(-1);
			response.setMessage("征信接口异常");
			return response;
		}

		Document doc = null;
		try {
			doc = DocumentHelper.parseText(responseXml);
			Element root = doc.getRootElement();
			Attribute retCodeAttr = root.attribute("retCode");
			Attribute scoreIDAttr = root.attribute("scoreID");
			Attribute scoreAttr = root.attribute("score");
			Attribute reasonAttr = root.attribute("reason");
			Attribute fraudAttr = root.attribute("fraud");
			Attribute profileAttr = root.attribute("profile");
			Attribute creditLimitAttr = root.attribute("creditLimit");
			Attribute approvalAttr = root.attribute("approval");
			Attribute baiAttr = root.attribute("bail");

			insertBean.setRetCode(retCodeAttr == null ? "" : retCodeAttr.getStringValue());
			insertBean.setScoreId(scoreIDAttr == null ? 0L : Long.parseLong(scoreIDAttr.getStringValue()));
			insertBean.setScore(scoreAttr == null ? 0 : Integer.parseInt(scoreAttr.getStringValue()));
			insertBean.setReason(reasonAttr == null ? "" : reasonAttr.getStringValue());
			insertBean.setFraud(fraudAttr == null ? 0 : Integer.parseInt(fraudAttr.getStringValue()));
			insertBean.setProfile(profileAttr == null ? "" : profileAttr.getStringValue());
			insertBean.setCreditLimit(creditLimitAttr == null ? 0 : Integer.parseInt(creditLimitAttr.getStringValue()));
			insertBean.setApproval(approvalAttr == null ? "" : approvalAttr.getStringValue());

			if (baiAttr != null) {
				if (baiAttr.getStringValue().indexOf(".") == -1) {
					insertBean.setBail(Integer.parseInt(baiAttr.getStringValue()));
				} else {
					insertBean.setBail(Integer
							.parseInt(baiAttr.getStringValue().substring(0, baiAttr.getStringValue().indexOf("."))));
				}
			} else {
				insertBean.setBail(0);
			}

			if (insertBean.getRetCode().equals("000")) {
				response.setCode(0);
				response.setMessage("成功返回数据");
			} else if (insertBean.getRetCode().equals("999")) {
				response.setCode(-1);
				response.setMessage("申请人数据无法匹配");
			} else {
				response.setCode(-1);
				response.setMessage("查询失败");
			}
		} catch (Exception e) {
			logger.error("【征信接口xml转换异常】", e);
			insertBean.setExceptionMessage(e.toString());
			insertBean.setExceptionState(1);
			ficoCreditInvestigationDao.insert(insertBean);
			response.setCode(-1);
			response.setMessage("征信接口xml转换异常");
			return response;
		}
		ficoCreditInvestigationDao.insert(insertBean);
		return response;
	}

	
	
//	/**
//	 * 查询近期征信记录情况
//	 * 
//	 * @param json
//	 * @param recentDays
//	 *            近期天数
//	 * @return
//	 */
//	private Boolean selectCreditByCondition(MobileCreateDto createDto) {
//		String idNumber = createDto.getIdNumber();
//		String fullName = createDto.getRealName();
//		String phoneNumber = createDto.getPhone();
//		Integer businessType = 1;
//		FicoCreditInvestigationBean investigationBean = new FicoCreditInvestigationBean();
//		investigationBean.setIdNumber(idNumber);
//		investigationBean.setFullName(fullName);
//		investigationBean.setPhoneNumber(phoneNumber);
//		investigationBean.setBusType(businessType);
//		List<FicoCreditInvestigationBean> investigationBeans = ficoCreditInvestigationDao
//				.selectByCondition(investigationBean);
//		if (CollectionUtils.isEmpty(investigationBeans)) {
//			return false;
//		} else {
//			TimeZone.setDefault(TimeZone.getTimeZone("GMT+8"));
//			Date now = new Date();
//			for (FicoCreditInvestigationBean ficoCreditInvestigationBean : investigationBeans) {
//				Date gmtCreate = ficoCreditInvestigationBean.getCreateTime();
//				Calendar cal = Calendar.getInstance();
//				cal.setTime(gmtCreate);
//				cal.add(Calendar.DATE, verifyDays);
//				if ((cal.getTime().compareTo(now) >= 0) && "000".equals(ficoCreditInvestigationBean.getRetCode())) {
//					return true;
//				}
//			}
//			return false;
//		}
//	}

}
